package com.baidu.speech.qr_code.ui.home;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.baidu.speech.qr_code.R;
import com.github.mummyding.colorpickerdialog.ColorPickerDialog;
import com.github.mummyding.colorpickerdialog.OnColorChangedListener;
import com.google.zxing.WriterException;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoActivity;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;

import org.litepal.LitePal;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import static com.baidu.speech.qr_code.ui.home.Code_image.zdycolor;

public class Home_MainActivity_setup extends TakePhotoActivity {
    private int [] colors = new int[]{Color.YELLOW,Color.BLACK,Color.BLUE,Color.GRAY,
            Color.GREEN,Color.CYAN,Color.RED,Color.DKGRAY, Color.LTGRAY,Color.MAGENTA,
            Color.rgb(100,22,33),Color.rgb(82,182,2), Color.rgb(122,32,12),Color.rgb(82,12,2),
            Color.rgb(89,23,200),Color.rgb(13,222,23), Color.rgb(222,22,2),Color.rgb(2,22,222)};
    private ImageView iv_setup;
    private Button bu_color;
    private Button bu_center;
    private Button bu_preservation;
    private Button bu_photograph;
    private Button bu_album;
    //二维码的封装类
    private Code_image code_image=new Code_image();
    //二维码的第三方库zxing
    private Bitmap zxing;
    //TakePhoto
    private TakePhoto takePhoto;
    private CropOptions cropOptions;  //裁剪参数
    private CompressConfig compressConfig;  //压缩参数
    private Uri imageUri;  //图片保存路径
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home__main_setup);
        try {
            initView();
            initData();
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }



    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);
        String iconPath = result.getImage().getOriginalPath();
        //Toast显示图片路径
        Toast.makeText(this, "imagePath:" + iconPath, Toast.LENGTH_SHORT).show();
        //Google Glide库 用于加载图片资源
//        Glide.with(this).load(iconPath).into(iv_setup);
        //接收HomeFragment的数据extra_data
        Intent intent1=getIntent();
        final String data=intent1.getStringExtra("extra_data1");
        Log.e("TAG", "initViewaa"+data);
        //获取Head_portrait数据库最新一张照片显示出来
        File file = new File(iconPath);
        try {
            FileInputStream fil =new FileInputStream(file);
            Bitmap bitmap = BitmapFactory.decodeStream(fil);
            //中间头像转成bitmap类型
            zxing = code_image.gainBitmap(bitmap);
            //加头像把头像放到二维码里 1.头像2.获取要转化成二维码的信息3.宽4.高
            try {
                zxing = code_image.makeQRImage(zxing,data,400,400,0xFF000000);
            } catch (WriterException e) {
                e.printStackTrace();
            }
            //图片引用zxing里的内容，zxing里的内容是data
            iv_setup.setImageBitmap(zxing);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //把最新图片路径保存在Head_Portrait数据库
        Core_log pstv_map1=new Core_log();
        pstv_map1.setHeadshot(iconPath);
        pstv_map1.save();
    }


    @Override
    public void takeFail(TResult result, String msg) {
        super.takeFail(result, msg);
        Toast.makeText(this, "Error:" + msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void takeCancel() {
        super.takeCancel();
    }
    private void initData() {
        ////获取TakePhoto实例
        takePhoto = getTakePhoto();
        //设置裁剪参数
        cropOptions = new CropOptions.Builder().setAspectX(1).setAspectY(1).setWithOwnCrop(false).create();
        //设置压缩参数
        compressConfig=new CompressConfig.Builder().setMaxSize(50*1024).setMaxPixel(800).create();
        takePhoto.onEnableCompress(compressConfig,true);  //设置为需要压缩
    }

    //获得照片的输出保存Uri
    private Uri getImageCropUri() {
        File file=new File(Environment.getExternalStorageDirectory(), "/temp/"+System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists())file.getParentFile().mkdirs();
        return Uri.fromFile(file);
    }


    //弹窗
    private void popup() {
        AlertDialog.Builder setDeBugDialog = new AlertDialog.Builder(this);
        final View dialogView = LayoutInflater.from(this).inflate(R.layout.notifications_popup, null);
        bu_photograph=dialogView.findViewById(R.id.bu_photograph);
        bu_photograph.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageUri = getImageCropUri();
                //拍照并裁剪
                takePhoto.onPickFromCaptureWithCrop(imageUri, cropOptions);
                //仅仅拍照不裁剪
                //takePhoto.onPickFromCapture(imageUri);
            }
        });
        bu_album=dialogView.findViewById(R.id.bu_album);
        bu_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageUri = getImageCropUri();
                //从相册中选取图片并裁剪
                takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);
                //从相册中选取不裁剪
                //takePhoto.onPickFromGallery();
            }
        });
        //将页面填充到AlertDiaLog容器
        setDeBugDialog.setView(dialogView);
        //  取消点击外部消失弹窗
        setDeBugDialog.setCancelable(true);
        final  AlertDialog customAlert=setDeBugDialog.show();
    }


    private void initView() throws WriterException {
        iv_setup = (ImageView) findViewById(R.id.iv_setup);
        //接收HomeFragment的数据extra_data
        Intent intent1=getIntent();
        final String data=intent1.getStringExtra("extra_data1");
        Log.e("TAG", "initViewaa"+data);
        Core_log pstv_map = LitePal.findLast(Core_log.class);
        //获取Head_portrait数据库最新一张照片显示出来
        File file = new File(pstv_map.getHeadshot());
        try {
            FileInputStream fil =new FileInputStream(file);
            Bitmap bitmap = BitmapFactory.decodeStream(fil);
            //中间头像转成bitmap类型
            zxing = code_image.gainBitmap(bitmap);
            //加头像把头像放到二维码里 1.头像2.获取要转化成二维码的信息3.宽4.高
            zxing = code_image.makeQRImage(zxing,data,400,400,0xFF000000);
            //图片引用zxing里的内容，zxing里的内容是data
            iv_setup.setImageBitmap(zxing);
        } catch (FileNotFoundException | WriterException e) {
            e.printStackTrace();
        }
        bu_color = (Button) findViewById(R.id.bu_color);
        bu_color.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ColorPickerDialog dialog = new ColorPickerDialog(Home_MainActivity_setup.this,colors)
                                .setOnColorChangedListener(new OnColorChangedListener() {
                                    @Override
                                    public void onColorChanged(int color) {
                                        //接收HomeFragment的数据extra_data
                                        Intent intent1=getIntent();
                                        final String data=intent1.getStringExtra("extra_data1");
                                        Log.e("TAG", "initViewaa"+data);
                                        Core_log pstv_map = LitePal.findLast(Core_log.class);
                                        //获取Head_portrait数据库最新一张照片显示出来
                                        File file = new File(pstv_map.getHeadshot());
                                        try {
                                            FileInputStream fil =new FileInputStream(file);
                                            Bitmap bitmap = BitmapFactory.decodeStream(fil);
                                            //中间头像转成bitmap类型
                                            zxing = code_image.gainBitmap(bitmap);
                                            //加头像把头像放到二维码里 1.头像2.获取要转化成二维码的信息3.宽4.高
                                            zxing = code_image.makeQRImage(zxing,data,400,400,color);
                                            //图片引用zxing里的内容，zxing里的内容是data
                                            iv_setup.setImageBitmap(zxing);
                                        } catch (FileNotFoundException | WriterException e) {
                                            e.printStackTrace();
                                        }
                                        Toast.makeText(getApplicationContext(),"Color "+color,Toast.LENGTH_SHORT).show();
                                    }})
                                .build()
                                .show();
            }
        });
        bu_center = (Button) findViewById(R.id.bu_center);
        bu_center.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popup();
            }
        });
        bu_preservation = (Button) findViewById(R.id.bu_preservation);
        bu_preservation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String Distdata=data;
                Intent intent=new Intent(Home_MainActivity_setup.this,Distinguish_code.class);
                intent.putExtra("Distinguish",Distdata);
                startActivity(intent);
            }
        });
    }
}